package com.mall.service.order.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.mall.commons.common.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/minio")
public class MinioController {

    @Value("${mall.basePath}")
    private String basePath;

    @PostMapping("/upload")
    public CommonResult uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + "\\" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.success(fileName);
    }

    @PostMapping("/delete")
    public CommonResult delFile(String objectName) {
        File file = new File(basePath + objectName);
        if (file.exists()) {
            file.delete();
        }
        return CommonResult.success(1, "删除成功");
    }
}
